define(function () {
    /**
     * @data
     *  title: 标题
     *  tools: 工具数据对象
     *  fnTools: 初始化工具回调, tools 或 fnTools
     *  fnImages: 返回 Images
     *  fnUploader: 获取上传参数
     *  fnHandle: 上传成功处理
     *  fnOperate: 对图片操作回调
     */
    return function (data) {
        var html = $(utils.getHtml('uploader', data)).appendTo('body');
        html.modal('show').on('hidden.bs.modal', function (e) {
            html.remove();
        });
        //如果没有设置 fnUploader, 使用默认的方式获取参数
        var defaultUploader = function () {
            return publicApi('upload_params');
        };
        //如果没有设置 fnTools, 使用默认的方式获取操作
        var tools = data.tools;
        var defaultTools = function (image) {
            if (!tools) {
                return '';
            }
            var html = '<div class="tools">';
            for (var operation in tools) {
                var tool = tools[operation];
                var disabled = '';
                if (image.image === tool.image) {
                    disabled = 'disabled="disabled"';
                }
                html += '<a ' + disabled + ' data-id="' + image.id + '" data-image="' + image.image + '" data-operation="' + operation + '" ' +
                    'href="javascript:;" class="img-operation btn btn-primary btn-sm ' + (tool.className || '') + '">' +
                    (tool.icon ? ' <i class="fa ' + tool.icon + '"></i> ' : '') + tool.text + '</a>';
            }
            html += '</div>';
            return html;
        }

        //加载图片
        var loadImages = function () {
            data.fnImages().then(function (data) {
                var images = data.rows, html = '';
                for (var i in images) {
                    var image = images[i];
                    html += '<div class="thumbnail pull-left" data-id="' + image.id + '"><img src="' + image.image + '?imageView2/2/h/320/q/75">' + (data.fnTools || defaultTools)(image) + '</div>';
                }
                $('#uploadImages').html(html);
            });
        }
        loadImages();

        /**
         * 初始化排序
         */
        for (var i in tools) {
            if (i === 'sort') {
                tools[i].className = (tools[i].className || '') + ' opt-sort';
                Sortable.create($('#uploadImages')[0], {
                    handle: '.opt-sort',
                    animation: 150,
                    onUpdate: function () {
                        var sorts = [];
                        $('#uploadImages .thumbnail').each(function (idx) {
                            sorts.push({order_by: idx, id: $(this).attr('data-id')});
                        });
                        return data.fnSort(sorts).then(function (result) {
                            if (result.success) {
                                utils.fixedAlert('success', '排序成功');
                            } else {
                                loadImages();
                                utils.fixedAlert('warning', result.message || '排序失败');
                            }
                        });
                    }
                });
            }
        }

        //初始化工具事件
        $('#uploadImages').on('click', '.thumbnail .img-operation', function () {
            var self = $(this);
            var id = self.attr('data-id'), operation = self.attr('data-operation'), image = self.attr('data-image');
            if (operation === 'remove') {
                utils.confirmation(self, {
                    placement: 'top',
                    optName: '删除图片',
                    title: '你确定删除该图片?',
                    fnConfirm: function () {
                        return data.fnOperate({id: id, operation: operation}).then(function (result) {
                            loadImages();
                            return result;
                        });
                    }
                });
            } else {
                data.fnOperate({id: id, operation: operation}).then(function (result) {
                    if (result.success) {
                        utils.fixedAlert('success', '操作成功');
                        var tools = data.tools;
                        if (tools && tools[operation].image) {
                            tools[operation].image = image;
                        }
                        loadImages();
                    } else {
                        utils.fixedAlert('warning', result.message || '操作失败');
                    }
                });
            }
        });

        //初始化上传
        (data.fnUploader || defaultUploader)().then(function (config) {
            Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: 'pickfiles',
                container: 'uploadContainer',
                dragdrop: true,
                drop_element: 'uploadContainer',
                max_file_size: '10mb',
                flash_swf_url: 'plupload/js/Moxie.swf',
                chunk_size: '4mb',
                unique_names: true,
                auto_start: true,
                uptoken_url: publicApi.uptoken_url,
                domain: config.domain,
                get_new_uptoken: false,
                init: {
                    'FilesAdded': function (up, files) {
                        $('#uploadQueue').show();
                        $('#uploadSuccess').hide();
                        plupload.each(files, function (file) {
                            //加入队列
                            var progress = new FileProgress(file, 'uploadProgress');
                            progress.setStatus("等待...");
                            progress.bindUploadCancel(up);
                        });
                    },
                    'BeforeUpload': function (up, file) {
                        var progress = new FileProgress(file, 'uploadProgress');
                        var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                        if (up.runtime === 'html5' && chunk_size) {
                            progress.setChunkProgess(chunk_size);
                        }
                    },
                    'UploadProgress': function (up, file) {
                        var progress = new FileProgress(file, 'uploadProgress');
                        var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                        progress.setProgress(file.percent + "%", up.total.bytesPerSec, chunk_size);
                    },
                    'UploadComplete': function () {
                        $('#uploadSuccess').show();
                    },
                    'FileUploaded': function (up, file, info) {
                        var progress = new FileProgress(file, 'uploadProgress');
                        progress.setComplete(up, info);
                        //成功后调用
                        var res = $.parseJSON(info);
                        data.fnHandle({
                            image: config.domain + res.key,
                            bucket: config.bucket,
                            key: res.key
                        }).then(function () {
                            loadImages();
                        });
                    },
                    'Error': function (up, err, errTip) {
                        $('#uploadQueue').show();
                        var progress = new FileProgress(err.file, 'uploadProgress');
                        progress.setError();
                        progress.setStatus(errTip);
                    }
                }
            });
        });
    }
});
